import { exec } from 'child_process'
import fs from 'fs'
import path from 'path'
import archiver from 'archiver'
import { Client } from 'ssh2'

const BUILD_CMD = 'npm run docs:build'
const BUILD_DIR = path.resolve('docs/.vitepress/dist')
const ZIP_PATH = path.resolve('sw_ui.zip') // 本地压缩包文件名
const PRIVATE_KEY_PATH = path.resolve('./shuwang.pem')  // 你的pem文件路径

const SERVER = {
  host: '47.120.1.66',
  port: 22,
  username: 'root',
  privateKey: fs.readFileSync(PRIVATE_KEY_PATH),
}

const REMOTE_ZIP_PATH = '/home/shuwang/sw_ui.zip'
const REMOTE_DIR = '/home/shuwang/sw_ui/dist'

function runBuild() {
  return new Promise((resolve, reject) => {
    console.log('🚀 开始本地打包...')
    exec(BUILD_CMD, (err, stdout, stderr) => {
      if (err) return reject(`打包失败: ${stderr}`)
      console.log(stdout)
      console.log('✅ 打包完成')
      resolve()
    })
  })
}

function zipBuildDir() {
  return new Promise((resolve, reject) => {
    console.log('📦 开始压缩打包文件夹...')
    const output = fs.createWriteStream(ZIP_PATH)
    const archive = archiver('zip', { zlib: { level: 9 } })

    output.on('close', () => {
      console.log(`✅ 压缩完成，大小: ${archive.pointer()} 字节`)
      resolve()
    })

    archive.on('error', err => reject(err))

    archive.pipe(output)
    archive.directory(BUILD_DIR, false) // 只打包dist下内容，不包含父目录
    archive.finalize()
  })
}

function deploy() {
  return new Promise((resolve, reject) => {
    const conn = new Client()
    conn.on('ready', () => {
      console.log('✅ SSH连接成功，开始上传zip...')
      conn.sftp((err, sftp) => {
        if (err) return reject(err)
        sftp.fastPut(ZIP_PATH, REMOTE_ZIP_PATH, err => {
          if (err) return reject(err)
          console.log('📤 上传完成，开始远程解压...')
          const cmd = `
            rm -rf ${REMOTE_DIR} && \
            mkdir -p ${REMOTE_DIR} && \
            unzip -o ${REMOTE_ZIP_PATH} -d ${REMOTE_DIR} && \
            rm -f ${REMOTE_ZIP_PATH}
          `
          conn.exec(cmd, (err, stream) => {
            if (err) return reject(err)
            stream.on('close', (code) => {
              console.log(`✅ 部署完成，退出码: ${code}`)
              conn.end()
              resolve()
            })
            stream.on('data', data => process.stdout.write(data))
            stream.stderr.on('data', data => process.stderr.write(data))
          })
        })
      })
    })
    .on('error', err => reject(err))
    .connect(SERVER)
  })
}

async function main() {
  try {
    await runBuild()
    await zipBuildDir()
    await deploy()
    console.log('🎉 全部完成')
  } catch (e) {
    console.error('❌ 失败:', e)
    process.exit(1)
  }
}

main()
